package cn.com.gridinfo.sooc.base.http;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.jeremy.arad.Arad;
import com.jeremy.arad.error.AradException;
import com.jeremy.arad.utils.Log;
import com.jeremy.arad.utils.StringUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;

import java.io.IOException;
import java.util.Map;

import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.core.login.common.CodeConst;

/**
 * SOOC Dao 请求链接
 * Created by jieli on 2015/9/2.
 */
public abstract class SoocIDao {
    protected SoocNetResult iNetResult;
    protected Context context;

    public SoocIDao(SoocNetResult iNetResult) {
        this.iNetResult = iNetResult;

        if (iNetResult instanceof Fragment) {
            context = ((Fragment) iNetResult).getActivity();
        } else if (iNetResult instanceof Activity) {
            context = (Activity) iNetResult;
        }
    }

    /**
     * 得到结果后，对结果处理逻辑
     *
     * @param result      网络请求返回的结果
     * @param requestCode 区别请求号码
     * @throws IOException
     */
    public abstract void onRequestSuccess(JsonNode result, int requestCode) throws IOException;


    /**
     * get请求网络，本方法提供结果的分发
     *
     * @param params
     */
    protected void getRequest(String url, Map<String, String> params) {
        _getRequest(url, params, 0,-1);
    }

    /**
     * get请求网络，带有请求编号
     *
     * @param params
     */
    protected void getRequestForCode(String url, Map<String, String> params, int requestCode) {
        _getRequest(url, params, requestCode,-1);
    }
    /**
     * get请求网络，带有请求编号
     * @param url
     * @param params
     * @param requestCode
     * @param isNeedToken  是否需要验证token
     */
    protected void getRequestForCode(String url, Map<String, String> params, int requestCode,int isNeedToken) {
        _getRequest(url, params, requestCode, isNeedToken);
    }

    private void _getRequest(String url, Map<String, String> params, final int requestCode,final int isNeedToken) {
        Log.d("url: ["+url+"]");
        RequestParams ajaxParams = new RequestParams(params);
        Log.d(AsyncHttpClient.getUrlWithQueryString(true, url, ajaxParams));

        Arad.http.get(context, url, ajaxParams, new TextHttpResponseHandler() {

            @Override
            public void onCancel() {
                super.onCancel();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseBody) {
                Log.d("接口返回结果:[" + responseBody + "]");
                try {
                    if (Arad.app.config.httpConfig != null) {
                        JsonNode node = Arad.app.config.httpConfig.handleResult(responseBody);
                        onRequestSuccess(node, requestCode);
                        iNetResult.onRequestSuccess(requestCode);
                    } else {
                        iNetResult.onRequestFaild(requestCode, "" + statusCode, responseBody);
                    }
                } catch (AradException e) {
                    Log.d("接口返回失败,抛出AradException异常:[" + e.getMessage() + "]");
                    iNetResult.onRequestFaild(requestCode, e.getError_code(), e.getMessage());
                } catch (JsonProcessingException e) {
                    Log.d("接口返回失败,抛出JsonProcessingException异常:[" + e.getMessage() + "]");
                    iNetResult.onRequestFaild(requestCode, e.getMessage(), e.getMessage());
                } catch (IOException e) {
                    Log.d("接口返回失败,抛出IOException异常:[" + e.getMessage() + "]");
                    iNetResult.onRequestFaild(requestCode, e.getMessage(), e.getMessage());
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) {
                Log.d("接口返回失败,statusCode:[" + statusCode + "] 返回内容:" + responseBody);
                if (statusCode == 0) {
                    //
                    if (isNeedToken == 0) {
                        iNetResult.onNoConnect();
                    } else {
                        if (StringUtils.isNull(Arad.preferences.getString(LocalMark.OUATH_TOKEN.getName(), ""))) {
                            iNetResult.onInvalidLogin();
                        } else {
                            iNetResult.onNoConnect();
                        }
                    }
//
                }
                else if(statusCode == 404 || statusCode==405){
                    iNetResult.onRequestFaild(requestCode, "" + statusCode, "无法加载服务器数据");
                }
                else {
                    iNetResult.onRequestFaild(requestCode, "" + statusCode, responseBody);
                }
            }
        });

    }

    /**************************************Post请求**********************/
    public void postRequest(String url, RequestParams params, int requestCode) {
        _postRequest(url,params,requestCode,-1);
    }

    public void postRequest(String url, RequestParams params, int requestCode, int isNeedToken) {
        _postRequest(url,params,requestCode,isNeedToken);
    }
    /**
     * POST 请求
     *
     * @param requestCode 自定义这是第几个post请求，用于结果的区分
     */
    public void _postRequest(String url, RequestParams params, final int requestCode,final int isNeedToken) {
        Log.d("URL:["+url+"]");
        Arad.http.post(context, url, params, new TextHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseBody) {
                try {
                    Log.d("接口返回内容:["+responseBody+"]");
                    if (Arad.app.config.httpConfig != null) {
                        JsonNode node = Arad.app.config.httpConfig.handleResult(responseBody);
                        onRequestSuccess(node, requestCode);
                    }
                    iNetResult.onRequestSuccess(requestCode);
                } catch (AradException e) {
                    Log.d("接口返回失败,抛出AradException异常:["+e.getMessage()+"]");
                    iNetResult.onRequestFaild(requestCode,e.getError_code(), e.getMessage());
                } catch (JsonProcessingException e) {
                    Log.d("接口返回失败,抛出JsonProcessingException异常:["+e.getMessage()+"]");
                    iNetResult.onRequestFaild(requestCode,e.getMessage(), e.getMessage());
                } catch (IOException e) {
                    Log.d("接口返回失败,抛出IOException异常:["+e.getMessage()+"]");
                    iNetResult.onRequestFaild(requestCode,e.getMessage(), e.getMessage());
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) {
                Log.d("接口返回失败,statusCode:[" + statusCode + "] 返回内容:" + responseBody);
                if (statusCode == 0) {
                    if(isNeedToken ==0){
                        iNetResult.onNoConnect();
                    }else {
                        if (StringUtils.isNull(Arad.preferences.getString(LocalMark.OUATH_TOKEN.getName(), ""))) {
                            iNetResult.onInvalidLogin();
                        } else {
                            iNetResult.onNoConnect();
                        }
                    }
                }
                else if(statusCode == 404 || statusCode==405 || statusCode == 500){
                    //500:服务器异常
                    iNetResult.onRequestFaild(requestCode, "" + statusCode, "无法加载服务器数据");
                }
                else {
                    Log.d("onFailure status Code:"+statusCode);
                    iNetResult.onRequestFaild(requestCode, "" + statusCode, responseBody);
                }
            }
        });

    }
}
